import './index.scss'

import classNames from 'classnames'
import React, { FunctionComponent, useRef, useState } from 'react'
import { View } from '@tarojs/components'

import api from '@/api'
import IconAirplane from '@/assets/icons/airplane.svg'
import { LxfButton } from '@/components'
import { IUploadOssRes } from '@/service/type'
import { useCommunication } from '@/hooks'

import LetterCard from '../components/letter-card'
import UploadCard from '../components/upload-card'
import { IFloatWrapperRef } from '@/components/lxf-float-wrapper'
import { LxfConfirmModal } from '@/components/lxf-confirm-model'

const baseCls = 'write-letter';

const WriteLetter: FunctionComponent<{}> = props => {
    const [imageList, setImageList] = useState<IUploadOssRes[]>([]);
    const [{ communicationInfo }] = useCommunication();
    const sendLetterConfirmRef = useRef<IFloatWrapperRef>(null);

    const deleteLetter = (file_id: number) => {
        setImageList(prev => prev.filter(image => image.file_id !== file_id))
    }

    const sendLetter = async () => {
        if (communicationInfo?.id) {
            const params = {
                cmmn_id: communicationInfo.id,
                letter_ids: imageList.map(image => image.file_id).join(','),
                remark: '打卡记录'
            }
            await api.lxf.writeLetter(params);
        }
    }

    return (
        <View className={baseCls}>
            <View className={classNames(`${baseCls}-wrapper`, {
                empty: imageList.length === 0
            })}>
                {imageList.length > 0 && imageList.map((image, index) => <LetterCard key={image.file_id} letterInfo={image} id={index + 1} onDelete={deleteLetter} />)}
                <UploadCard onUpload={(image: IUploadOssRes) => setImageList((prev) => prev.concat(image))} />
                {imageList.length === 0 && <View>
                    <View className={`${baseCls}-title`}>打开相机</View>
                    <View className={`${baseCls}-content`}>逐页拍摄你的手写信件</View>
                </View>}
                <View className={`${baseCls}-sendbtn`}>
                    <LxfButton title={'投递信件'} icon={IconAirplane} onClick={() => sendLetterConfirmRef.current?.open()} />
                </View>
            </View>
            <LxfConfirmModal
                ref={sendLetterConfirmRef}
                title={'确定投递你的信件？'}
                showCancelBtn
                showOkBtn
                okText={"投递"}
                onOk={sendLetter}
                componentProps={{ content: '请先按照顺序阅读你上传的信件，一旦投递，信件将不可撤回。' }}
            />
        </View>
    );
};

export default WriteLetter;
